class LifecycleDemoPlugin {
    apply(compiler) {
        // 1. 初始化阶段钩子
        compiler.hooks.initialize.tap('LifecycleDemo', () => {
            console.log('1. initialize: 初始化阶段');
        });

        // 2. 读取配置后
        compiler.hooks.entryOption.tap('LifecycleDemo', (context, entry) => {
            console.log('2. entryOption: 入口配置处理');
            console.log('   Entry Points:', Object.keys(entry));
        });

        // 3. 开始编译
        compiler.hooks.compile.tap('LifecycleDemo', (params) => {
            console.log('3. compile: 开始编译');
        });

        // 4. 创建 compilation 对象后
        compiler.hooks.compilation.tap('LifecycleDemo', (compilation) => {
            console.log('4. compilation: 创建 compilation 对象');

            // compilation 的额外钩子
            compilation.hooks.buildModule.tap('LifecycleDemo', (module) => {
                console.log('   ↳ buildModule:', module.identifier());
            });
        });

        // 5. 收集依赖前
        compiler.hooks.make.tapAsync('LifecycleDemo', (compilation, callback) => {
            console.log('5. make: 开始分析依赖');
            setTimeout(() => {
                console.log('   ↳ 模拟异步操作完成');
                callback();
            }, 100);
        });

        // 6. 生成资源前
        compiler.hooks.thisCompilation.tap('LifecycleDemo', (compilation) => {
            // 处理资源的新方式
            compilation.hooks.processAssets.tapPromise(
                {
                    name: 'LifecycleDemo',
                    stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
                },
                async (assets) => {
                    console.log('6. processAssets: 处理资源阶段');

                    const meta = {
                        buildTime: new Date().toISOString(),
                        assets: Object.keys(assets),
                        chunks: Array.from(compilation.chunks).map(chunk => chunk.name)
                    };

                    assets['meta.json'] = {
                        source: () => JSON.stringify(meta, null, 2),
                        size: () => JSON.stringify(meta).length
                    };
                }
            );
        });

        // 7. 生成资源后
        compiler.hooks.afterEmit.tap('LifecycleDemo', (compilation) => {
            console.log('7. afterEmit: 资源已写入磁盘');
        });

        // 8. 完成构建
        compiler.hooks.done.tap('LifecycleDemo', (stats) => {
            console.log('8. done: 构建完成');
            console.log('   Duration:', stats.toJson().time + 'ms');
            console.log('   Output:', stats.toJson().outputPath);
        });

        // 9. 失败处理
        compiler.hooks.failed.tap('LifecycleDemo', (error) => {
            console.error('! 构建失败:', error);
        });
    }
}

module.exports = LifecycleDemoPlugin;